package leetcode

import kotlinetc.println

//https://leetcode.com/problems/word-break/
/**
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

Note:

The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:

Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:

Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Example 3:

Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false
 */
fun main(args: Array<String>) {

    wordBreak("catsandog", listOf("cats", "dog", "sand", "and", "cat")).println()
    wordBreak("applepenapple", listOf("apple", "pen")).println()

}

/**
 * 使用动态规划来做：思路简单，对于[0,i] ([0,i]+[i,j])   dp[i]记录之前的数组是否可以被分割，
 * 然后对 [i,j]范围内的子串是否包含在字典中
 */
fun wordBreak(s: String, wordDict: List<String>): Boolean {

    val dp = Array(s.length + 1, { false })  //初始化length+1
    val wordSet = wordDict.toHashSet()
    dp[0] = true /*wordSet.contains(s[0].toString())*/  //这里下标指的是s长度，不是索引.所以空串为true，不然后面的dp判断跑不下去，全都为false
    for (i in 0 until s.length + 1)
        for (j in 0 until i+1) {
            if (dp[j] && wordSet.contains(s.substring(j, i))) {//这个判断条件要求dp[0]必须为true
                dp[i] = true
                break
            }
        }
    return dp.last()
}